#include "httpclient.h"

#include "curl/curl.h"
#include "curl/easy.h"


// Write to String
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
	((std::string*) userp)->append((char*)buffer, 0, size*nmemb);
	return size * nmemb;
}


HttpClient::HttpClient()
{
}

int HttpClient::Get(std::string url, std::string& resp)
{
  CURL* handle = curl_easy_init();

  if (handle) {
    CURLcode code;
    curl_easy_setopt(handle, CURLOPT_URL, url.c_str());

    resp.clear();
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &resp);

    code = curl_easy_perform(handle);
    curl_easy_cleanup(handle);
    return code;
  } 

  return -1;
}

int HttpClient::Post(std::string url, std::string json, std::string& resp)
{
  CURL* handle = curl_easy_init();

  struct curl_slist* headers = NULL;
  

  if (handle) {
    CURLcode code;
    curl_easy_setopt(handle, CURLOPT_URL, url.c_str());

    resp.clear();
    headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
    
    curl_easy_setopt(handle, CURLOPT_POSTFIELDS, json.c_str());
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &resp);
    curl_easy_setopt(handle, CURLOPT_POST, 1);

    code = curl_easy_perform(handle);

    curl_slist_free_all(headers);
    curl_easy_cleanup(handle);

    return code;
  } 

  return -1;
}
